﻿@inherits BaseComponent
@typeparam TItem where TItem : class, new()

<Table TItem="TItem" IsBordered ShowEmpty ShowExtendButtons
       ShowExtendEditButton="false" ShowExtendDeleteButton="false"
       IsPagination="Model.ShowPager" PageItemsSource="[10,20,50,100]" OnQueryAsync="OnQueryAsync">
     <TableColumns>
         <BootGenerateColumns Table="Model" Item="context" />
     </TableColumns>
     <RowButtonTemplate>
        @if (Model.Actions != null && Model.Actions.Count > 0)
        {
            var actions = Model.RowActions?.Invoke(context);
            if (actions == null)
                actions = Model.Actions;
            @if (actions.Count > 2)
            {
                var first = actions[0];
                var firstName = Language.GetString(first);
                <TableCellButton Color="first.ToColor()" Text="@firstName" OnClick="e=>Model.OnAction?.Invoke(first, context)" />
            }
            else
            {
                foreach (var item in actions)
                {
                    var itemName = Language.GetString(item);
                    <TableCellButton Color="item.ToColor()" Text="@itemName" OnClick="e=>Model.OnAction?.Invoke(item, context)" />
                }
            }
        }
    </RowButtonTemplate>
</Table>

 @code {
    [Parameter] public TableModel<TItem> Model { get; set; }

    protected override void OnInitialized()
    {
        Model.OnRefresh = RefreshAsync;
        base.OnInitialized();
    }

    public async Task RefreshAsync()
    {
        Model.Result = await Model.OnQuery?.Invoke(Model.Criteria);
        StateHasChanged();
    }

    private async Task<QueryData<TItem>> OnQueryAsync(QueryPageOptions options)
    {
        Model.Criteria.PageIndex = options.PageIndex;
        Model.Criteria.PageSize = options.PageItems;
        Model.Result = await Model.OnQuery?.Invoke(Model.Criteria);
        return new QueryData<TItem>
        {
            TotalCount = Model.Result.TotalCount,
            Items = Model.Result.PageData
        };
    }
}